<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\AdminController;
use think\facade\Cache;
use think\facade\Log;

class Upload extends AdminController
{
    /**
     * 图片上传
     * @return array|\think\response\Json
     */
    public static function uploadImages()
    {
        $pathname = isset($_REQUEST['path']) ? $_REQUEST['path'] : 'default';

        $file = $_FILES['file']['tmp_name'];

//        var_dump($_FILES);exit;

        $file = self::base64EncodeImage($file);
        if (empty($file)) {
            return json(['code' => 0, 'msg' => '参数错误1']);
        }
        $imageName = self::rands();

        if (!preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            return ['code' => 0, 'msg' => '参数错误2'];
        }

        //获取图片后缀
        $type = $result[2];

        $new_file = "/public/" . $pathname . "Image/" . date('Ymd', time()) . "/";
        $new_file2 = "/public/" . $pathname . "Image/" . date('Ymd', time()) . "/";
        $fullpath = $_SERVER['DOCUMENT_ROOT'] . $new_file;
        if (!file_exists($fullpath)) {
            @mkdir($fullpath, 0775, true);
        }
        $fullpath = $fullpath . $imageName . ".{$type}";
        $new_file = $new_file . $imageName . ".{$type}";

        if (!file_put_contents($fullpath, base64_decode(str_replace($result[1], '', $file)))) {
            return ['code' => 0, 'msg' => '图片生成失败'];
        }

        $source = $_SERVER['DOCUMENT_ROOT'] . $new_file2 . $imageName . ".{$type}";//原图文件名
        $percent = 1;  #原图压缩，不缩放，但体积大大降低
        (new \upload\Upload($source, $percent))->compressImg($source);

        return json(['code' => 1, 'msg' => 'success', 'data' => ['src' => $new_file]]);
    }

    /**
     * 图片转base64
     * @param $image_file
     * @return string
     */
    private static function base64EncodeImage($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    /**
     * 拼接随机字符
     * @return string
     */
    private static function rands()
    {
        return md5(date("His", time()) . "_" . rand(1111, 9999)) . uniqid();
    }


    /**
     * 视频上传
     * @param $file
     * @param string $path
     * @return \think\response\Json
     */
    public static function uploadVideo()
    {
        $file = $_FILES['file'];
        $path = $_REQUEST['path'] ?: 'default';
        // 获取文件类型
        $ext = strtolower(pathinfo(@$file['name'], PATHINFO_EXTENSION));
        $date = '/public/' . $path . 'Video/' . date('Ymd');
        $fullpath = $_SERVER['DOCUMENT_ROOT'] . $date;
        // 目录是否存在
        if (!file_exists($fullpath)) {
            @mkdir($fullpath, 0775, true);
        }
        // 生成唯一的文件名
        $fileName = md5(date('Ymd') . time()) . '.' . $ext;
        // 将文件名拼接到指定的目录下
        $destName = $fullpath . "/" . $fileName;
        // 进行文件移动
        if (!move_uploaded_file($file['tmp_name'], $destName)) {
            return json(['code' => 0, 'msg' => 'error', 'data' => '上传失败']);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => $date . '/' . $fileName]);
    }

    /**
     * 图片/视频删除
     * @param $path
     * @return \think\response\Json
     */
    public static function delImageOrVideo($path)
    {
        $filePath = $_SERVER['DOCUMENT_ROOT'] . $path;
        if (file_exists($filePath)) {
            @unlink($filePath);
            return json(['code' => 1, 'msg' => 'success']);
        }
    }

    /**
     * 大文件上传
     * @return \think\response\Json
     */
    public function maxFieldsUpload()
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Content-type: text/html; charset=gbk32");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $folder = input('folder');
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
        usleep(5000);

        $topDir = '/public' . DIRECTORY_SEPARATOR;
        // 存放分片临时目录
        $targetDir = $_SERVER['DOCUMENT_ROOT'] . $topDir . 'file_uploads_tmp';


        // 分片合并存放目录
        if ($folder) {

            $subDir = $topDir . 'file_uploads' . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . date('Ymd');

            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $subDir;

        } else {
            $subDir = $topDir . 'file_uploads' . DIRECTORY_SEPARATOR . date('Ymd');

            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . $subDir;

        }

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;

        $fileName = iconv('UTF-8', 'gb2312', $fileName);
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory111."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file)) {
                    Log::write('file:' . json_encode($file), 'error');
                    if (file_exists($tmpfilePath)) {
                        Log::write('file_exists:' . json_encode($tmpfilePath), 'error');
                        // 文件上次的修改时间
                        if (@filemtime($tmpfilePath) < time() - $maxFileAge) {
                            @unlink($tmpfilePath);
                        }
                    }
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream222."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file333."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream444."}, "id" : "id"}');
            }
        } else {
            if (!$in = fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream555."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        fclose($out);
        fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }

        if ($done) {
            $pathInfo = pathinfo($fileName);
            $hashStr = substr(md5($pathInfo['basename']), 8, 16);
            $hashName = time() . $hashStr . '.' . $pathInfo['extension'];
            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $hashName;
            $uploadPath1 = DIRECTORY_SEPARATOR . $hashName;
            if (!$out = fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream666."}, "id" : "id"}');
            }
            //flock($hander,LOCK_EX)文件锁
            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    fclose($in);
                    unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            fclose($out);

            $response = [
                'success' => true,
                'oldName' => $oldName,
                // 把反斜杠(\)替换成斜杠(/) 因为在windows下上传路径是反斜杠径
                'filePath' => str_replace("\\", "/", $uploadPath),
                'subFilePath' => str_replace("\\", "/", $subDir . $uploadPath1),
//                'fileSize'=>$data['size'],
                'fileSuffixes' => $pathInfo['extension'],          //文件后缀名
//                'file_id'=>$data['id'],
            ];

            $r = Cache::set($response['subFilePath'], $response['oldName']);
            Log::write('cacheKey：' . $response['subFilePath'], 'error');
            Log::write('cacheValue：' . $response['oldName'], 'error');
            Log::write('cacheRes：' . $r, 'error');

            return json($response);
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

}